<!--
 * @Author: chenhuanhuan 2925102113@qq.com
 * @Date: 2025-02-13 10:05:26
 * @LastEditors: chenhuanhuan 2925102113@qq.com
 * @LastEditTime: 2025-03-05 10:33:18
 * @FilePath: \hbzc-groupmeal-center-web\src\centerViews\recipePlan\recipeTemplate\components\createConfig.vue
-->
<template>
  <div class="flex flex-1" v-loading="loading">
    <div class="left-box">
      <p v-for="(item, index) in leftList" :key="index" @click="changeWeek(item, index)" class="week-item"
        :class="weekIdx == item.value ? 'active-week' : ''">
        {{ item.label }}</p>
    </div>
    <div class="right-box ">
      <div class="flex justify-end mb-4">
        <el-tooltip class="box-item" effect="dark" content="同步上一天菜谱" placement="top-end">
          <pb-button plain size="small" v-if="showSynchro" @click="synchroRecipe">同步</pb-button>
        </el-tooltip>
        <pb-button size="small" class="ml-6" @click="saveRecipe">保存模板</pb-button>
      </div>
      <div>
        <el-tabs v-model="curMeal" class="demo-tabs" @tab-change="handleClick">
          <el-tab-pane v-for="(item, index) in recipeAllData" :key="index" :label="item.mealTimesName" :name="index">
            <div class="static-box">
              <p class="static-item">配餐总数：<span>{{ totalType.countSum }}</span></p>
              <p class="static-item" v-for="(it, key, idx) in totalType.countItem" :key="idx">{{ key }}：<span>{{ it
              }}</span></p>
            </div>
            <pb-table border :column="recipeColumn" :tableData="item.details" height="360">
              <template #dishType="{ row }">
                <div>
                  <pb-select-tags :List="typeList" :checkList="[row.dishTypeCode]" isSingle
                    :defaultProps="{ label: 'dishTypeName', value: 'dishTypeCode' }"
                    @change="(val) => changeTag(val, row, 'type', item)"></pb-select-tags>
                </div>
              </template>
              <template #material="{ row }">
                <div>
                  <pb-select-tags :List="materialList" :checkList="row.materialCategoryIdArr"
                    :defaultProps="{ label: 'dishAttributeValue', value: 'dishAttributeValueId' }"
                    @change="(val) => changeTag(val, row, 'material')"></pb-select-tags>
                </div>
              </template>
              <template #operate="{ row }">
                <PopconfirmButton @confirm="deleteFn(row, item)"></PopconfirmButton>
              </template>
            </pb-table>
            <div class="mt-6  btn-css">
              <pb-button secondary size="small" @click="addRecipe(item)"> +添加规则 </pb-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getRecipeTemplateDay, setRecipeTemplateDay, getTemplatePramas } from '@/api/Recipe'
import { createAlert } from '@/Public-UIlibrary/pb-alert/method';
import { createMsgBox } from '@/Public-UIlibrary/pb-message-box/method';
import { createMessage } from '@/Public-UIlibrary/pb-message/method';
import { useDebounceFn, useThrottleFn } from "@vueuse/core";

const props = defineProps({
  weekVal: {
    type: Number
  }
})

const curTab = ref(1)
const leftList = ref([])
const weekIdx = ref(0)

const selectList = reactive([
  { label: '周一', value: 1 }, { label: '周二', value: 2 }, { label: '周三', value: 3 }, { label: '周四', value: 4 }, { label: '周五', value: 5 }, { label: '周六', value: 6 }, { label: '周日', value: 7 },])

watch(
  () => props.weekVal,
  (val) => {
    let copyList = JSON.parse(JSON.stringify(selectList))
    const section = copyList.splice(val - 1)
    copyList.unshift(...section)
    leftList.value = copyList
  },
)

const recipeColumn = reactive([
  {
    slot: "dishType",
    width: 200,
    name: "菜品分类",
  },
  {
    slot: "material",
    width: 200,
    name: "原料",
  },
  {
    slot: "operate",
    width: 60,
    name: "操作",
  },
])
// 表格插入数据
const addRecipe = (item) => {
  item.details.push({ dishTypeCode: "", dishTypeName: '', materialCategoryIdArr: [], key: Math.random().toString() })
}

// 某一天的表格数据
const recipeAllData = ref([])

// 删除数据
const deleteFn = async (row, item) => {
  isSave.value = false
  let idx = item.details.findIndex(el => el.key == row.key)
  item.details.splice(idx, 1)
}


// 标签改变时修改表格数据
const changeTag = async (val, row, type, item) => {
  isSave.value = false
  if (type == 'type') {
    let { dishTypeCode, dishTypeName } = typeList.value.find(type => type.dishTypeCode == val[0].dishTypeCode)
    row.dishTypeCode = dishTypeCode
    row.dishTypeName = dishTypeName
  } else if (type == 'material') {
    row.materialCategoryIdArr = []
    row.materialCategoryIdArr = val.map(el => el.dishAttributeValueId)
  }
}

// 动态计算每餐菜肴类型
const totalType = computed(() => {
  let arr = recipeAllData.value[curMeal.value].details
  let obj = {}
  const countBy = arr.reduce((acc, item) => {
    if (item.dishTypeCode) {
      acc[item.dishTypeName] = (acc[item.dishTypeName] || 0) + 1;
    }
    return acc;
  }, {});
  obj.countSum = 0;
  for (const key in countBy) {
    obj.countSum += countBy[key];
  }
  obj.countItem = countBy;
  return obj
})

// 重新计算菜品总量
const reViewDishNum = (item) => {
  return new Promise<void>((resolve, reject) => {
    let countItem = {}
    let countSum = null
    const arr = []
    item.details.map(it => {
      let typeObj = typeList.value.find(type => type.dishTypeCode == it.dishTypeCode)
      arr.push(typeObj)
    });
    const countBy = arr.reduce((acc, item) => {
      acc[item.dishTypeName] = (acc[item.dishTypeName] || 0) + 1
      return acc
    }, {})
    for (const key in countBy) {
      countSum += countBy[key]
    }
    countItem = countBy

    resolve({ countItem, countSum })
  })
}


// 餐段数据
const mealList = ref([])
const curMeal = ref(0)


// 菜品、原料分类
const typeList = ref([])
const materialList = ref([])


// 是否展示同步按钮
const showSynchro = ref(false)
const changeWeek = useThrottleFn((item, idx) => {
  if (!isSave.value) {
    createMsgBox(
      '您尚未保存编辑内容，离开数据将会丢失，请保存',
      { cancelText: '不保存' }).then(res => {
        if (res) {
          saveRecipe()?.then(res => {
            curMeal.value = 0
            weekIdx.value = item.value
            showSynchro.value = leftList.value[0].value == weekIdx.value ? false : true
            getRecipeTemplateDayApi()
            isSave.value = true
          })
        } else {
          curMeal.value = 0
          weekIdx.value = item.value
          showSynchro.value = leftList.value[0].value == weekIdx.value ? false : true
          getRecipeTemplateDayApi()
          isSave.value = true
        }
      })

  } else {
    curMeal.value = 0
    weekIdx.value = item.value
    showSynchro.value = leftList.value[0].value == weekIdx.value ? false : true
    getRecipeTemplateDayApi()
    isSave.value = true
  }
}, 400)


// 判断数据是否被改变且保存
const isSave = ref(true)
// 保存当前模板
const saveRecipe = (msg: string = '保存成功') => {
  let judgeNull
  let mealName
  recipeAllData.value.forEach(el => {
    el.details.forEach(element => {
      if (element.materialCategoryIdArr.length == 0 || el.countSum == 0) {
        judgeNull = true
        mealName = el.mealTimesName
      }
    });
  })
  if (judgeNull) {
    createAlert({
      type: 'error',
      alert: `请完善 ${mealName} 菜谱模版信息`
    })
  } else {
    loading.value = true;
    return new Promise<void>((resolve, reject) => {
      let params = {
        week: weekIdx.value,
        timesDataList: recipeAllData.value
      }
      setRecipeTemplateDay(params).then(res => {
        if (res.code == 2000) {
          loading.value = false;
          isSave.value = true
          resolve(true)
          createMessage({
            message: msg
          })
        }
      })
    })

  }
}

// 同步上一天菜谱
const synchroRecipe = () => {
  createMsgBox(
    '同步上一天菜谱将覆盖当前添加菜谱，是否同步？',
    { cancelText: '不同步', confirmText: '同步' }).then(res => {
      if (res) {
        loading.value = true
        let idx = leftList.value.findIndex(el => el.value == weekIdx.value)
        getRecipeTemplateDay({ week: leftList.value[idx - 1].value }).then(async res => {
          if (res.code == 2000) {
            res.data.forEach(el => {
              el.details.map(it => {
                it.recipeTemplateDetailId = ''
                return it
              })
            })
            recipeAllData.value = await formatRecipeData(res.data)
            loading.value = false;
            saveRecipe('同步成功')
          }
        })
      }
    })
}

const loading = ref(false)
// 按天查询食谱模板参数
const getRecipeTemplateDayApi = () => {
  loading.value = true;
  return new Promise<void>((resolve, reject) => {
    getRecipeTemplateDay({ week: weekIdx.value }).then(async res => {
      loading.value = false
      if (res.code == 2000) {
        recipeAllData.value = await formatRecipeData(res.data)
      }
    })
  })
}

// 给每一天的数据添加菜品总量数据
const formatRecipeData = (data) => {
  return new Promise<void>((resolve, reject) => {
    data.forEach(el => {
      if (el.details.length) {
        let arr = []
        el.details.map(it => {
          it.key = Math.random().toString()
          let typeObj = typeList.value.find(type => type.dishTypeCode == it.dishTypeCode)
          arr.push(typeObj)
        });
      }
      resolve(data)
    })
  })
}

// 查询模板参数
const getTemplatePramasApi = () => {
  return new Promise<void>((resolve, reject) => {
    getTemplatePramas().then(res => {
      if (res.code == 2000) {
        let { mealTimesList, materialCategoryList, dishTypeList } = { ...res.data }
        mealList.value = mealTimesList
        materialList.value = materialCategoryList
        typeList.value = dishTypeList
      }
    })
  })
}

const onInit = (date) => {
  weekIdx.value = date
  getRecipeTemplateDayApi()
}

onMounted(() => {
  getTemplatePramasApi()
})

defineExpose({ onInit })
</script>

<style lang="scss" scoped>
.left-box {
  // height: 100%;
  padding-right: 16px;
  width: 200px;
  box-sizing: border-box;
  box-shadow: inset -1px 0px 0px 0px rgba(0, 0, 0, 0.1)
}

.right-box {
  padding: 16px;
  box-sizing: border-box;
  width: calc(100% - 200px);
}

.week-item {
  height: 48px;
  text-align: center;
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 16px;
  color: rgba(0, 0, 0, 0.65);
  line-height: 48px;
  border-radius: 4px;
  margin-bottom: 16px;
  cursor: pointer;
}

.active-week {
  background: #0D968B;
  color: #FFFFFF;
}

.static-box {
  width: 88%;
  display: flex;
  align-items: center;
  margin: 6px 0 16px 0;
  font-size: 14px;
  font-family: PingFang SC, PingFang SC;

  .static-item {
    margin-right: 24px;
    font-weight: 400;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.65);
    line-height: 22px;

    span {
      font-weight: 600;
      font-size: 18px;
      color: rgba(0, 0, 0, 0.85);
      line-height: 28px;
    }
  }
}
</style>